var upTimeOut = null;
$(function(){
  initFileUploadFun();
});

function initFileUploadFun()
{
//关闭文件上传浮层
  $(".fileFloatBox .btn-close").live('click', function(){
    $(".fileFloatBox").addClass('hidden');
    $(".fileFloatBox li").remove();
  });
  
  // 文件上传
  var _input = $(".addFile");
  
  var fileFloatBox = $(".fileFloatBox");
  if (fileFloatBox.length < 1) {
    fileFloatBox = $('<div class="fileFloatBox float04 float-div hidden">\
                      <div class="fl-top04 clearfix">\
                          <span class="fs16 left">正在上传:<span class="uploaded-num">1</span>/<span class="total-num">10</span></span>\
                          <div class="btn-icon right">\
                            <a href="javascript:;" class="btn-close"></a>\
                          </div>\
                      </div>\
                      <ul class="file-list">\
                      </ul>\
                  </div>');
    $('body').append(fileFloatBox);
  }
  //多点上传
  _input.each(function(){
    if ($(this).find(":input[type='file']").length > 0) {
      return;
    }
    
    var appResName = $(this).attr('data-res-name');
    var appResId   = $(this).attr('data-res-id');
    var fileId   = $(this).attr('data-file-id');
    
    // 上传地址
    var upUrl = siteUrl+'/core/handler/file_uploader';
      // 在其它应用中上传文件
      if (typeof appResName != 'undefined') {
          upUrl += '?app_res_name='+appResName;
        if (typeof appResId != 'undefined') {
          upUrl += '&app_res_id='+appResId;
        }
        
      // 直接在文件系统中上传文件
      } else if (typeof dirId != 'undefined') {
        upUrl += '?dir_id='+dirId;
      }
      
      // 更新文件版本
      if (typeof fileId != 'undefined') {
        if (upUrl.indexOf('?') != '-1') {
          upUrl += '&';
        } else {
          upUrl += '?';
        }
        upUrl += 'file_id='+fileId;
      }
    
    
    var upload_file = $.exts.upload(this, {
      action:upUrl,
      inputName: 'xfile',
      params:{ 'source':'ajaxuploader' },
      //预览
      beforeUpload:function(e){
        //显示个数
        fileFloatBox.removeClass('hidden');
        //console.log('上传前预览文件信息11', e);
        //console.log('上舒心', upload_file._files);
        //console.log('上舒心_queue', upload_file._queue);
        //console.log('上舒心_loaded', upload_file._loaded);
        var attach = $('<li class="clearfix" queue_id="'+e.id+'">\
                        <div class="file-infor left">\
                          <img src="'+siteUrl+'/images/task/icons-03.png" alt="">\
                          <a href="#" class="file-name">'+e.name+'</a>\
                        </div>\
                        <div class="file-icons right">\
                          <span class="progress-bar2"><a href="javascript:void(0);" class="green"></a></span>\
                          <span class="percent">0%</span>\
                          <a href="javascript:;" class="icon-close"></a>\
                        </div>\
                      </li>');
        attach.appendTo(fileFloatBox.children('ul'));
        
        var totalNum = fileFloatBox.find('.file-list li').length;
        fileFloatBox.find('.total-num').html(totalNum);
        
        loadImage(e.obj, function(n) {
          if (!n) {
              var t = "/js/upload/file_icons/"; //后缀图片目录
              i = t + "file_extension_" + e.extension + ".png";
              loadImage(i, 
              function(n) {
                  //n ? attach.find("img").attr("src", n.src) : attach.find("img").attr("src", t + "file_extension_others.png");
              })
          } else attach.find("img").attr({
              //src: n.src
          }).css("cursor", "pointer");
        });
        
        if (window.File && window.FileList) {
            var fileSize = 0;
            e.size >= 1048576 ? fileSize = (e.size / 1048576).toFixed(1) + "M": fileSize = (e.size / 1024).toFixed(0) + "K";
        } else {
          attach.find(".progress-bar2").remove();
          attach.find(".percent").html('uploading..'); //图片替换
        }
        attach.addClass("uploading");
        attach.find(".size").text(fileSize);
        
        //取消上传
        attach.find('.icon-close').click(function(e){
          e.preventDefault();
          var attach = $(this).closest('li');
          var id = attach.attr("queue_id");
          
          //取消 上传队列
          if(attach && attach.removeClass("uploading")){
            upload_file.cancel(id);
          }
          attach.removeClass("uploading").fadeOut();
          var file_id = attach.attr("file_id");
          if (file_id) {
            alert(file_id);
          }
        });
      },
      //进度
      onProgress: function(e, t, n) {
        //console.log('------------------------------------successs---------------');
          //console.log('上舒心', upload_file._files);
          //console.log('上舒心_queue', upload_file._queue);
          //console.log('上舒心_loaded', upload_file._loaded);
        var totalNum = fileFloatBox.find('.total-num').html();
        var uploadedNum = parseInt(totalNum) - upload_file._queue.length + 1;
        fileFloatBox.find('.uploaded-num').html(uploadedNum);
        ////console.log('上传进度');
        ////console.log('e',e); //文件信息
        ////console.log('t',t); //已上传
        ////console.log('n',n); //总大小
        i = (t / n * 100).toFixed(0) + "%";
        ////console.log(i); //百分比
        var r = fileFloatBox.find("li[queue_id=" + e.id + "]");
        i = (t / n * 100).toFixed(0) + "%";
        r.find(".progress-bar2 .green").width(i);
        r.find(".percent").text(i);
      },
        //完成
      onSuccess: function(e, t) {
        ////console.log('文件信息',e);
        ////console.log(t);
        var t = $.parseJSON(t);
        ////console.log('response内容', t);
        if (t.info !='ok'){
          alert(t.info);
          //upload_file.onCancel(e);
          return;
        }
        var n = fileFloatBox.find("li[queue_id=" + e.id + "]");
        n.find(".progress-bar2, .percent").remove();
        n.removeClass("uploading").attr("file_id", t.id).find(".icon-close").removeClass('icon-close').addClass('icon-success');
        
        var html = '';
        if (upload_file._elem) {
          if (upload_file._elem.hasClass('taskDetailAdd')) {
            html = '<li class="clearfix" id="file_'+t.id+'" data-res-id="'+appResId+'">\
                      <div class="annex-box annex-box-details left">\
                          <img src="'+siteUrl+'/images/task/icons-03.png" width="20" height="12" alt="">\
                      </div>\
                      <div class="del-update del-update-details left">';
                      //knowledgeDetail
              if (!upload_file._elem.hasClass('knowledgeDetail') && appResId != upload_file._elem.attr('data-res-id')) {
                html += '<a href="'+siteUrl+'/file/'+t.id+'" target="_blank" class="black">'+t.title+'<span style="margin-left:3px;font-size:12px;">来自:'+upload_file._elem.attr('data-res-id')+'</span></a>&nbsp;&nbsp;'
              } else {
                html += '<a href="'+siteUrl+'/file/'+t.id+'" target="_blank" class="black">'+t.title+'</a>&nbsp;&nbsp;';
              }
                   html += '<p class="smallControlBox btn-edit-details hidden">\
                          <a href="javascript:;" class="addFile smallListFile btn-del-update btn-update2" data-res-name="'+appResName+'" data-res-id="'+appResId+'" data-file-id="'+t.id+'">修改</a>&nbsp;|&nbsp;\
                          <a href="javascript:;" class="deleteFile btn-del-update btn-update2">删除</a>\
                        </p>\
                      </div>\
                    </li>';
            $(".taskFileBox").removeClass('hidden');
            $(".fileList").append(html);
            if (!$(".taskFileAdd").hasClass('hidden')) {
              $(".fileList .smallControlBox").removeClass('hidden');
            }
          } else if (upload_file._elem.hasClass('smallListFile')) {
          } else if (upload_file._elem.hasClass('fileDetailUp')){
            var currFileId = upload_file._elem.attr('data-file-id');
            location.href = siteUrl+'/file/'+currFileId;
          } else if (upload_file._elem.hasClass('fileListAdd')) {
            var _tmpPreview = siteUrl+t.middle;
            if (t.real_path) {
              _tmpPreview = t.real_path;
            }
            html = '<li id="file_'+t.id+'" class="file"  data-version="version">\
                      <a href="'+siteUrl+'/file/'+t.id+'">\
                        <span class="img">\
                          <img src="'+_tmpPreview+'" alt="">\
                        </span>\
                        <span class="file-name">'+t.title+'</span>\
                      </a>\
                    </li>';
            $(".fileList").prepend(html);
            //$(".noFile").remove();
            if ($(".fileList li").length > 0) {
              $(".emptyBox").addClass('hidden');
              $(".noMore").addClass('hidden');
            } else {
              $(".emptyBox").removeClass('hidden');
            }
          }
        }
        
        checkTimeout();
        //更新预览图片
        //mcw.loadImage(t.file_path, 
      },
      //取消上传中或还没上传的附件
      onCancel: function(e) {},
      onError: function(e, t) {
        //console.log(e, t);
      },
      //不管上传成功不成功都执行
      onComplete: function(e, t) {
        //console.log(this);
          if (upload_file.getInProgress() === 0) {
            //显示提交
            //var n = u.parents("form:first").find("button[type=submit]");
          }
      },
      //前台验证后缀, 
      onValidate: function(e, t) {
        //console.log('文件信息',e);
        ////console.log('后缀名',t);
        var allow_type = ['jpg', 'png', 'gif', 'jpeg', 'bmp', 'flv', 'swf', 'rar', 'zip', 'msoffice', 'xls', 'xlsx', 'doc', 'docx', 'txt', 'psd'];
        t.toLowerCase();
        //var allow_type = ['jpg', 'png', 'gif', 'jpeg', 'bmp', 'flv', 'swf', 'rar', 'zip', 'doc', 'msoffice', 'xls', 'txt', 'psd'];
        //if($.inArray(t, allow_type) == -1 ){
        if ('php' == t) {
          showMsg("不允许的上传类型:"+t);
          return !1;
        } 
        
        if(e.size > 20971520){
          showMsg('文件大小不能起过20M');
          return !1;
        } 

        return !0;
      },
      onError: function(e, t) { }
    });
  }); //多点上传
}

function checkTimeout()
{
  var i = 0;
  if ($(".fileFloatBox li .progress-bar2").length == 0) {
    upTimeOut = setTimeout('destoryFloatFileBox()', 1500);
  } else {
    if (upTimeOut != null) {
      clearTimeout(upTimeOut);
    }
  }
}

function destoryFloatFileBox()
{
  $(".fileFloatBox li").remove();
  $(".fileFloatBox").addClass('hidden');
  upTimeOut = null;
}